package logic

import (
	"cart_srv/models"
	"cart_srv/pkg"
	"context"
	"errors"

	"cart_srv/cart"
	"cart_srv/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *cart.LoginRequest) (*cart.LoginResponse, error) {
	// todo: add your logic here and delete this line
	//用户登录注册
	var u models.User
	u.Mobile = in.Mobile
	//查找用户
	err := u.GetUserByMobile()
	if err != nil {
		logx.Error("登录失败:查找用户失败", err)
		return nil, err
	}
	//未注册
	if u.ID == 0 {
		//注册
		u.Password = pkg.Md5(in.Password)
		err = u.Register()
		if err != nil {
			logx.Error("登录失败:用户注册失败", err)
			return nil, err
		}
	} else {
		//登录
		if u.Password != pkg.Md5(in.Password) {
			logx.Error("登录失败:", errors.New("密码错误"))
			return nil, errors.New("密码错误")
		}
	}

	return &cart.LoginResponse{UserId: int64(u.ID)}, nil
}
